import nodeFetch from 'node-fetch'
import type { WebviewContent } from './webviewContent'

const captureUrls = ['/api/project/images', '/api/project/image']

// 捕获蓝湖设计稿的响应
export const capture = (
    webContents: Electron.WebContents,
    webviewContentInstance?: InstanceType<typeof WebviewContent>
) => {
    // 外面已经挂载了debugger，这里就不用再加载了
    // try {
    //     webContents.debugger.attach('1.3')
    // } catch (err) {
    //     console.log('Debugger attach failed: ', err)
    // }

    webContents.debugger.on('detach', (_event, reason) => {
        console.log('Debugger detached due to: ', reason)
    })

    webContents.debugger.on('message', async (_event, method, params) => {
        // 如果不是网络响应事件则忽略
        if (method !== 'Network.responseReceived') {
            return
        }
        // 如果路径不包含需要捕获
        const url = params.response.url as string
        if (!captureUrls.some((v) => url.includes(v))) {
            return
        }
        // 如果响应不是json格式则忽略
        const contentType = params.response.headers['content-type']
        if (!contentType.includes('application/json')) {
            return
        }
        const res = await webContents.debugger.sendCommand('Network.getResponseBody', { requestId: params.requestId })
        // console.log(params.response.url)
        // console.log(666, JSON.parse(res?.body))
        webviewContentInstance?.emit('response-received', {
            url,
            response: JSON.parse(res?.body)
        })
    })

    webContents.debugger.sendCommand('Network.enable')
}

// 另一种捕获方式，就是重新请求一遍
export const capture2 = (webContents: Electron.WebContents) => {
    // key: id-url
    const captureCache: {
        [key: string]: {
            url: string
            beforeRequest?: Electron.OnBeforeRequestListenerDetails
            beforeHeaders?: Electron.OnBeforeSendHeadersListenerDetails
            response?: any
        }
    } = {}

    webContents.session.webRequest.onBeforeSendHeaders(
        { types: ['xhr'], urls: ['<all_urls>'] },
        async (details, cb) => {
            // console.log(details)
            cb({ cancel: false })
            if (captureCache[details.url]) {
                return
            }
            if (details.resourceType === 'xhr' && captureUrls.some((v) => details.url.includes(v))) {
                captureCache[details.url] = {
                    url: details.url
                }
                console.log(details.url, details.method, details.requestHeaders)
                const res = await nodeFetch(details.url, {
                    method: details.method,
                    headers: details.requestHeaders
                })
                const body = await res.json()
                console.log(body)
                // captureCache[details.id] = {
                //     url: details.url,
                //     response: body
                // }
                // console.log('captureCache', captureCache)
            }
        }
    )
}
